package com.shawn.dubbo.service;

import com.shawn.model.mongo.Friend;
import com.shawn.model.mongo.Movement;
import com.shawn.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //开启多线程查询保存
    public void saveTimeline(Long userId, Movement saveMovement) {
        //查找所有好友
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId))
                .fields().include("friendId");
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //更新时间线表维护可见好友数据
        for (Friend friend : friends) {
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(saveMovement.getId());
            timeLine.setUserId(userId);
            timeLine.setFriendId(friend.getFriendId());
            timeLine.setCreated(new Date().getTime());
            //保存数据
            mongoTemplate.save(timeLine);
        }
    }

}
